<?php
/**
 * Created by phpstorm.
 * User: Chain
 * Date: 2020/11/23
 * Time: 11:56
 */

namespace App\Http\Controllers\Upload;


use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Common\Exception\ErrorException;
use Illuminate\Http\File;

class UploadController extends Controller
{
    private $acceptedType = [
        'pdf' => 'pdf/',
        'mp3' => 'audio/',
        'mp4' => 'video/',
        'doc' => 'word/',
        'docx' => 'word/',
        'xlsx' => 'excel/',
        'xls' => 'excel/',
        'ppt' => 'ppt/',
        'pptx' => 'pptx/',
        'other'=> 'image/'
    ];

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->middleware('auth');
    }

     /**
     * 文件上传
     * @author lxy
     * @datetime 2021-03-02
     */
    public function upload(Request $request)
    {  
        $files = $request->file('file');
        if($files->isValid()){
            //获取文件类型
            $extension = $files->getClientOriginalExtension();
            $folder = $this->acceptedType[$extension] ?? $this->acceptedType['other'];
            $path = Carbon::now()->format('Ymd');
            $tempName = md5($files->getClientOriginalName().uniqid().$path).'.'.$extension;
            $newPath = $folder.date('Ymd');
            $file = Storage::disk('Uploads')->putFileAs($newPath, new File($files),$tempName);
            return [
                'code' =>1,
                'data' => [
                    'url' => Storage::disk('Uploads')->url($file),
                    'file_name' => $files->getClientOriginalName(),
                    'size' => $files->getClientSize(),
                    'date' => date("Y-m-d H:i:s")
                ]              
            ];

        }else{
            return ['code'=>9,'msg'=>'提交失败'];
        }
    }

    //文件下载-不删除文件
    public function FileDownload()
    {
        $file_url = request()->get('file_url','');  //真实文件路径
         $filename = request()->get('filename','');  //真实文件名
          if ($file_url == ''){
              throw new ErrorException('文件不存在');
          }
         $headers=[
             "Content-Disposition"=>"attachment; filename=".$filename,
             "Content-Transfer-Encoding"=>" binary",
             "Content-Type"=> $this->get_content_type($filename)
         ];
         return response()->download(public_path($file_url),$filename,$headers)->deleteFileAfterSend(false);
    }

    //文件下载-删除文件
    public function FileDownloadDel()
    {  
        $file_url = request()->get('file_url','');  //真实文件路径
        $filename = request()->get('filename','');  //真实文件名
         if ($file_url == ''){
             throw new ErrorException('文件不存在');
         }
        $headers=[
            "Content-Disposition"=>"attachment; filename=".$filename,
            "Content-Transfer-Encoding"=>" binary",
            "Content-Type"=> $this->get_content_type($filename)
        ];
        return response()->download(public_path($file_url),$filename,$headers)->deleteFileAfterSend(true);
    }
 
     //zip文件下载
     public function zipDownload()
     {
         $real_name = request()->get('file_name');
         $url = public_path('download/zip/') . $real_name;
         $ext = strtolower(pathinfo($real_name,PATHINFO_EXTENSION ));
         if (strtolower($ext) == 'zip'){
             $content_type = "application/x-zip-compressed";
         }else{
             throw new ErrorException('格式不正确');
         }
 
         $headers=[
             "Content-Disposition"=>"attachment; filename=" . $real_name,
             "Content-Transfer-Encoding"=>" binary",
             "Content-Type"=> $content_type
         ];
         if (!file_exists($url)){
             throw new ErrorException('文件生成失败!');
         }
 
         return response()->download($url,$real_name,$headers)->deleteFileAfterSend();
 
     }
 
     private function get_content_type($filename) {
 
         $mime_types = array(
 
             'txt' => 'text/plain',
             'htm' => 'text/html',
             'html' => 'text/html',
             'php' => 'text/html',
             'css' => 'text/css',
             'js' => 'application/javascript',
             'json' => 'application/json',
             'xml' => 'application/xml',
             'swf' => 'application/x-shockwave-flash',
             'flv' => 'video/x-flv',
 
             // images
             'png' => 'image/png',
             'jpe' => 'image/jpeg',
             'jpeg' => 'image/jpeg',
             'jpg' => 'image/jpeg',
             'gif' => 'image/gif',
             'bmp' => 'image/bmp',
             'ico' => 'image/vnd.microsoft.icon',
             'tiff' => 'image/tiff',
             'tif' => 'image/tiff',
             'svg' => 'image/svg+xml',
             'svgz' => 'image/svg+xml',
 
             // archives
             'zip' => 'application/zip',
             'rar' => 'application/x-rar-compressed',
             'exe' => 'application/x-msdownload',
             'msi' => 'application/x-msdownload',
             'cab' => 'application/vnd.ms-cab-compressed',
 
             // audio/video
             'mp3' => 'audio/mpeg',
             'qt' => 'video/quicktime',
             'mov' => 'video/quicktime',
 
             // adobe
             'pdf' => 'application/pdf',
             'psd' => 'image/vnd.adobe.photoshop',
             'ai' => 'application/postscript',
             'eps' => 'application/postscript',
             'ps' => 'application/postscript',
 
             // ms office
             'doc' => 'application/msword',
             'rtf' => 'application/rtf',
             'xls' => 'application/vnd.ms-excel',
             'ppt' => 'application/vnd.ms-powerpoint',
 
             // open office
             'odt' => 'application/vnd.oasis.opendocument.text',
             'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
         );
 
         $ext = strtolower(pathinfo($filename,PATHINFO_EXTENSION ));
 
         if (array_key_exists($ext, $mime_types)) {
             return $mime_types[$ext];
         } else {
             return 'application/octet-stream';
         }
     }
      
}
